package com.gcloud.mesh.common.runner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.cache.LogModuleCache;
import org.jeecg.common.cache.UserPermissionCache;
import org.jeecg.config.IscConfig;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.IPermissionService;
import org.jeecg.modules.system.service.IUserService;
import org.jeecg.modules.system.util.IscUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sgcc.isc.core.orm.complex.FunctionNode;
import com.sgcc.isc.core.orm.complex.FunctionTree;
import com.sgcc.isc.core.orm.identity.User;
import com.sgcc.isc.core.orm.resource.Function;
import com.sgcc.isc.service.adapter.factory.AdapterFactory;
import com.sgcc.isc.service.adapter.helper.IIdentityService;
import com.sgcc.isc.service.adapter.helper.IResourceService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Component
public class UserPermissionCacheRunner implements CommandLineRunner {

	@Autowired
	private IPermissionService permissionService;

	@Autowired
	private IUserService userService;

	@Autowired
	private SysUserMapper sysUserMapper;

	@Override
	public void run(String... args) throws Exception {
		long start = System.currentTimeMillis();
		log.info("【用户权限加载-UserPermissionCache】开始");
		try {
			Map<String, String> syncUsernameMap = new HashMap<>();

			IIdentityService identityService = AdapterFactory.getIdentityService();

			if (StringUtils.isNotBlank(IscConfig.getIscUsernamePrefix())) {
				String[] iscUsernamePrefixs = IscConfig.getIscUsernamePrefix().split(",");
				for (String iscUsernamePrefix : iscUsernamePrefixs) {
					List<User> iscUsers = identityService.getUsersByName(iscUsernamePrefix);
					if (iscUsers != null) {
						for (User iscUser : iscUsers) {
							String res = syncUsernameMap.get(iscUser.getUserName());
							if (res == null) {
								syncUsernameMap.put(iscUser.getUserName(), iscUser.getId());
								log.info("【用户权限加载-UserPermissionCache】ISC用户名（" + iscUser.getUserName() + "）加入同步数组");
							}
						}
					}
				}
			}

			List<SysUser> dbUsers = sysUserMapper.selectList(new QueryWrapper<SysUser>());
			if (dbUsers != null && dbUsers.size() > 0) {
				for (SysUser user : dbUsers) {
					String res = syncUsernameMap.get(user.getUsername());
					if (res == null) {
						syncUsernameMap.put(user.getUsername(), user.getId());
						log.info("【用户权限加载-UserPermissionCache】DB用户名（" + user.getUsername() + "）加入同步数组");
					}
				}
			}

			if (syncUsernameMap.size() > 0) {
				for (Map.Entry<String, String> entry : syncUsernameMap.entrySet()) {
					String username = entry.getKey();
					String userId = entry.getValue();
					try {
						// 同步用户
						SysUser sysUser = userService.getUserByName(username);
						if (sysUser == null) {
							userService.syncUser(userId, username);
							log.info("【用户权限加载-UserPermissionCache】userName:" + username + ", 同步用户成功！");
						}

						JSONObject jsonCache = permissionService.getPermissionByUsername(username);
						if (jsonCache != null) {
							// 保存内存
							UserPermissionCache.put(username, jsonCache);
							log.info("【用户权限加载-UserPermissionCache】userName:" + username + ", 加入内存成功！");
						}
					} catch (Exception e) {
						log.error("【用户权限加载-UserPermissionCache】userName:" + username + ", 失败", e);
					}
				}
			}
			log.info("【用户权限加载-UserPermissionCache】成功，耗时:" + (System.currentTimeMillis() - start) + "毫秒");
			
			
			log.info("【日志模块加载-UserPermissionCache】开始");
			List<SysUser> allUser = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("third_type", "isc"));
			if (allUser != null) {
				for (SysUser user : allUser) {
					if (StringUtils.isNotBlank(user.getThirdId())) {
						Map<String, String> map = LogModuleCache.getByUserId(user.getId());
						if (map == null) {
							map = IscUtil.getLogModule(user.getId());
							if (map != null) {
								LogModuleCache.put(user.getId(), map);
							}
						}
					}
				}
			}
			
			log.info("【日志模块加载-UserPermissionCache】结束");
			
		} catch (Exception e) {
			log.error("【用户权限加载-UserPermissionCache】失败，" + e.getMessage(), e);
		}
	}
	
}